﻿namespace EasyGo.Data
{
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;

    public class SqlUnitOfWork : IUnitOfWork
    {
        protected SqlConnection _connection;
        protected SqlTransaction _transaction;
        protected bool _disposed;
        protected bool _completed;

        public SqlUnitOfWork()
        {
            _connection = new SqlConnection(ConfigurationManager.ConnectionStrings["data"].ConnectionString);
            _connection.Open();
            _transaction = _connection.BeginTransaction(IsolationLevel.ReadCommitted);
        }

        public IDbCommand GetStoredProcedureCommand(string text)
        {
            var command = _connection.CreateCommand();
            command.CommandType = CommandType.StoredProcedure;
            command.Transaction = _transaction;
            command.CommandText = text;
            return command;
        }

        public void CommitChanges()
        {
            _transaction.Commit();
            _completed = true;
        }

        public virtual void PartialComplete()
        {
            _transaction.Commit();
            _transaction = _connection.BeginTransaction(IsolationLevel.ReadCommitted);
        }

        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }
            _disposed = true;
            if (!_completed)
            {
                _transaction.Rollback();
                _transaction.Dispose();
                _transaction = null;
            }
            _connection.Close();
            _connection.Dispose();
            _connection = null;
        }
    }
}
